package com.fs.flow.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.fs.base.vo.JsonResponse;
import com.fs.flow.pojo.JFormFlow;
import com.fs.flow.repository.JFormDesignRepository;
import com.fs.flow.repository.JFormFlowRepository;
import com.fs.flow.repository.JFormRepository;

/**
 * 表单处理器
 *
 */
@Controller
@RequestMapping("/console/jFormFlow/rewrite")
public class JFormFlowController {
	private static final Logger log = Logger.getLogger(JFormFlowController.class); 
	@Autowired private JFormRepository jFormRepository;
	@Autowired private JFormDesignRepository jFormDesignRepository;
	@Autowired private JFormFlowRepository jFormFlowRepository;
	
	
	@GetMapping("design")
	public String design(String formId,HttpServletRequest request){
		return "/console/jFormFlow/design";
	}
	
	@GetMapping("preView")
	public String preView(String formId,HttpServletRequest request){
		return "/console/jFormFlow/preView";
	}
	
	@ResponseBody
	@RequestMapping("/getJson")
	public JSONObject getJson(String flowId) {
		JSONObject json = new JSONObject();
		try {
			JFormFlow flow = jFormFlowRepository.findOne(flowId);
			if(flow!=null){
				json.put("data", flow);
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return json;
	}
	
	
	/**
	 * @param flowId
	 * @param jsonData
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/designSave")
	public JsonResponse designSave(String flowId,String jsonData,HttpServletRequest request) {
		try {
			JFormFlow flow = jFormFlowRepository.findOne(flowId);
			if(flow!=null && StringUtils.isNotBlank(jsonData)){
				flow.setFlowJson(jsonData);
				flow.setFlowStatus("已设计");
				jFormFlowRepository.save(flow);
			}
			return JsonResponse.success();
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return JsonResponse.error(e.getMessage());
		}
	}
	
}
